package com.cositas.dulces.lp.promo2012;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Game;
import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.cositas.dulces.lp.promo2012.utils.ActionsPoints;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class GameFinishedAction implements Action {
	
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws EntityNotFoundException, IOException {
		String uid = req.getParameter("uid"); // el que invita
		String game = req.getParameter("game"); // el que invita
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Key wallShareKey = KeyFactory.createKey(Game.entity_name, uid + "-" + System.nanoTime());
		// circuito de puntaje
		Key participantKey = KeyFactory.createKey(Participant.entity_name, uid);
		Entity participant = datastore.get(participantKey);
		Integer account = Integer.valueOf((String)participant.getProperty(Participant.field_points));
		int points = 0;
		if ("memo".equals(game)) {
			points = ActionsPoints.MEMO_GAME_POINTS;
		}
		if ("puzzle".equals(game)) {
			points = ActionsPoints.PUZZLE_GAME_POINTS;
		}
		account = account + points;
		participant.setProperty(Participant.field_points, account.toString());
		datastore.put(participant);
		Entity wallShare = new Entity(wallShareKey);
		wallShare.setProperty(Game.field_date, new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
		if ("memo".equals(game)) {
			wallShare.setProperty(Game.field_code, "memo");
		}
		if ("puzzle".equals(game)) {
			wallShare.setProperty(Game.field_code, "puzzle");
		}
		
		datastore.put(wallShare);
		resp.getWriter().print("OK");
	}
}
